package cn.com.nes.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class ValidCodeUtil {

	private static List<Map<String,Object>> codeMap = new ArrayList<Map<String,Object>>();
	private static final char[] codeChar = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz234567890".toCharArray();
	private static final char[] numChar = "0123456789".toCharArray();
	// 验证码长度
	private static final int CODE_LEN = 4;
	
	//生成code
	public static String generateCode(String phone) {
		String validCode = "";
		Map<String,Object> map = new HashMap<String,Object>();
		Random random = new Random();
		for(int i = 0; i < CODE_LEN; i++) {
			int index = random.nextInt(numChar.length);
			String str = numChar[index] + "";
			validCode += str;
		}
		long millis = System.currentTimeMillis();
		map.put("code", validCode);
		map.put("phone",phone );
		map.put("expires", millis+1000*60*5);
		//addCodeMap(map);
		return validCode;
	}

	//验证code
	public static boolean validCode(String phone,String code) {
		boolean result = false;
		Iterator<Map<String, Object>> iterator = codeMap.iterator();
		while(iterator.hasNext()) {
			
			Map<String, Object> next = iterator.next();
			if(phone.equals(next.get("phone")) && code.equals(next.get("code"))
					&& Long.parseLong(String.valueOf(next.get("expires")))>System.currentTimeMillis()) {
				result = true;
			}
			
			//过期删除 
			if(Long.parseLong(String.valueOf(next.get("expires")))<System.currentTimeMillis()) {
				iterator.remove();
			}
		}
		return result;
	}
	
	//插入对象到缓存
	public static void addCodeMap(Map<String,Object> map) {
		int flag = 0;
		String phone = (String) map.get("phone");
		String code = (String) map.get("code");
		Long expires = (Long) map.get("expires");
		Iterator<Map<String, Object>> iterator = codeMap.iterator();
		while(iterator.hasNext()) {
			Map<String, Object> next = iterator.next();
			//判断是否存在手机号 存在就覆盖
			if(phone.equals(next.get("phone"))) {
				flag = 1;
				next.put("code", code);
				next.put("expires", expires);
			}
		}
		//手机号不存在就插入
		if(flag!=1) {
			codeMap.add(map);
		}
	}
	public static void main(String[] args) {
//		String phone = "15704661884";
//		String validCode = "3138";
//		boolean result = validCode(phone, validCode);
//		System.out.println(result);
		
		String generateCode = generateCode("15704661884");
		System.out.println(codeMap);
		String generateCode1 = generateCode("15704661884");
		System.out.println(codeMap);
	}
}
